from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse

# Create your views here.

from myadmin import models
from django.contrib.auth.hashers import make_password, check_password
from web.settings import BASE_DIR
import os
import time


# 前台首页
def index(request):
    # 获取所有的一级分类
    data = models.Cates.objects.filter(pid = 0)
    
    # 获取当前一级分类下的二级分类
    for x in data:
        x.sub = models.Cates.objects.filter(pid = x.id)
    context = {'data':data}

    '''
    # 数据存储的结构
    [
        'name':'点心/蛋糕',
            'sub':[
                'name':'点心','goodslist':[
                        goodsobject,goodsobject
                    ],
                'name':'蛋糕','goodslist':[
                        goodsobject,goodsobject
                    ]
                ],
        'name':'饼干/膨化','sub':['name':'饼干','goodslist':[goodsobject,goodsobject],'name':'膨化','goodslist':[goodsobject,goodsobject]]
    ]
    '''
    return render(request,'myhome/index.html',context)



# 商品列表页
def goodslist(request,uid):
    
    ob = models.Goods.objects.filter(cateid = uid).order_by(request.GET.get('orderby','id'))
    num = models.Goods.objects.filter(cateid = uid).count()

    for i in ob:
        obs = i
    context = {'cateslist':ob,'num':num,'obs':obs}
    return render(request,'myhome/list.html',context)



# 商品详情页
def goodsinfo(request):
    # 获取商品的id
    cid = request.GET.get('cid') 
    
    # 根据商品id获取商品信息
    ob  = models.Goods.objects.get(id = cid)
    catlist = models.Cates.objects.get(id = ob.cateid.id)
    print(ob.cateid)
    context = {'data':ob,'catlist':catlist}
    return render(request,'myhome/info.html',context)



# 将商品加入购物车
def cartadd(request):
    # 根据id 商品数量 用户id
    goods = models.Goods.objects.get(id = request.GET.get('cid'))
    user = models.Users.objects.get(id = request.session['Vip']['id'])
    num = int(request.GET.get('num'))

    # 检查当前购买的商品是否已经存在在购物车中
    res = models.Cart.objects.filter(goodsid = goods).filter(uid = user)
    if res.count():
        # 为真表示商品已存在
        for v in res:
            v.num +=num
            v.save()
    else:
        # 为假
        ob = models.Cart(goodsid = goods,uid = user,num = num)
        # print(ob)
        ob.save()
    return JsonResponse({'error':0,'msg':'加入购物车成功'})



# 修改购物车
def cartedit(request):
    # 获取 id 数量
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')

    ob = models.Cart.objects.get(id = cartid)
    ob.num = int(num)
    ob.save()

    # 运算小计
    totalprice = ob.num * ob.goodsid.price
    return JsonResponse({'error':0,'msg':'修改成功','totalprice':"{:.2f}".format(totalprice)})



# 删除购物信息
def cartdel(request):
    # 接收 cartids
    cartids = eval(request.GET.get('cartids'))
    print(cartids)
    data = models.Cart.objects.filter(id__in=cartids)
    for ob in data:
        ob.delete()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myhome_cartindex')+'"</script>')


def cartdelOne(request):
    # 接收 cartids
    gid = request.GET.get('gid')
    
    ob = models.Cart.objects.get(id = gid)
    ob.delete()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myhome_cartindex')+'"</script>')




# 确认订单
def orderconfirm(request):
    # 接收 cartids
    cartids = eval(request.GET.get('cartids'))   
    # 获取对应的购物车数据
    data = models.Cart.objects.filter(id__in=cartids)
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level = 1)
    # 分配数据
    context = {'data':data,'citys':citys}
    # 加载模板
    return render(request,'myhome/confirm.html',context)






# 订单创建
def ordercreate(request):
    # 获取提交订单的订单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # ------------------------------添加订单---------------------------------------
    # 获取用户对象
    user = models.Users.objects.get(id = request.session['Vip']['id'])
    # 获取地址信息
    addr = models.Address.objects.get(id = data['addressid'])
    sheng = models.Citys.objects.get(id = addr.sheng).name
    shi = models.Citys.objects.get(id = addr.shi).name
    xian = models.Citys.objects.get(id = addr.xian).name
    # 字符串拼接成收货地址
    shdz = sheng + shi + xian + addr.info
    # 计算总价
    totalprice = 0
    cart = models.Cart.objects.filter(id__in = eval(data['cartids']))
    for x in cart:
        totalprice += x.num * x.goodsid.price

    # 准备订单数据
    orderdata = {'uid':user,'shr':addr.shr,'shdh':addr.shdh,'shdz':shdz,'buytype':data['buytype'],'wl':data['wl'],'totalprice':totalprice}

    # 创建订单
    order = models.Order(**orderdata)
    order.save()
    # 生成订单详情
    for x in cart:
        odinfo = models.OrderInfo()
        odinfo.orderid = order
        odinfo.goodsid = x.goodsid.id
        odinfo.title = x.goodsid.title
        odinfo.pic_url = x.goodsid.pic_url
        odinfo.price = x.goodsid.price
        odinfo.num = x.num
        # 添加到订单详情
        odinfo.save()
        # 删除购物车中已经下单的商品
        x.delete()
    # print(totalprice)
    # print(orderdata)
    return HttpResponse('<script>alert("订单创建成功,请前往支付");location.href="/order/buy/?orderid='+str(order.id)+'"</script>')





# 订单支付页面
def orderbuy(request):
    # 订单号
    orderid = request.GET.get('orderid')
    data = models.Order.objects.get(id = orderid)
    context = {'data':data}
    return render(request,'myhome/success.html',context)




# 我的订单
def myinfo_order(request):
    # 获取当前用户
    uid = models.Users.objects.get(id=request.session['Vip']['id'])
    user = models.Order.objects.filter().exclude(status = 5)
    print(user)
    # 获取待付款的商品
    dfk = models.Order.objects.filter(uid = uid).filter(status = 0)
    # 获取待发货的商品
    dfh = models.Order.objects.filter(uid = uid).filter(status = 1)
    # 获取待收货的商品
    dsh = models.Order.objects.filter(uid = uid).filter(status = 2)
    # 获取待评价的商品
    dpj = models.Order.objects.filter(uid = uid).filter(status = 3)
    # 分配数据
    context = {'user':user,'dfk':dfk,'dfh':dfh,'dsh':dsh,'dpj':dpj}
    # 加载模板
    return render(request,'myhome/myinfo/order.html',context)


# 删除订单
def myinfo_delorder(request):
    # 获取删除的商品id
    uid = request.GET.get('uid')
    data = models.Order.objects.get(id = uid)
    data.status = 5
    data.save()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myhome_myinfo_order')+'"</script>')


# 个人资料
def myinfo_introduction(request):
    # 获取当前用户
    user = models.Users.objects.get(id=request.session['Vip']['id'])
     # 判断请求方式
    if request.method == 'GET':  
        # 分配数据
        context = {'data':user}
        return render(request,'myhome/myinfo/introduction.html',context)
    elif request.method == 'POST':
        # 接收手机号
        phone = request.POST.get('phone')
        # 到数据库查询
        num = models.Users.objects.filter(phone=phone).count()
        if num and user.phone != phone:
            return HttpResponse('<script>alert("该号码已注册");history.back(-1);</script>')
        # 执行编辑
        user.username = request.POST.get('username')
        user.phone = request.POST.get('phone')
        user.email = request.POST.get('email')
        user.age = request.POST.get('age')
        user.sex = request.POST.get('sex')
        # user.save()
        return HttpResponse('<script>alert("更新成功,请重新登录");location.href="'+reverse('myhome_logout')+'"</script>')




# 地址管理
def myinfo_address(request):
    # 获取地址
    data = models.Address.objects.filter(uid=request.session['Vip']['id']).values()
    for x in data:
        x['sheng'] = models.Citys.objects.get(id=x['sheng']).name
        x['shi'] = models.Citys.objects.get(id=x['shi']).name
        x['xian'] = models.Citys.objects.get(id=x['xian']).name
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level=1) 
    # 分配数据
    context = {'data':data,'citys':citys}
    # 加载模板
    return render(request,'myhome/myinfo/address.html',context)



# 地址删除
def myinfo_deladdress(request):
    uid = request.GET.get('uid')
    # print(uid + '4555')
    data = models.Address.objects.get(id = uid)
    data.delete()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myhome_myinfo_address')+'"</script>')



# 个人中心设置默认地址
def myinfo_editaddress(request):
    # 获取想要设置地址的默认地址
    aid = request.GET.get('aid')
    addr = models.Address.objects.get(id=aid)
    addr.isChecked=1
    addr.save()
    op = models.Users.objects.get(id=request.session['Vip']['id'])
    addrs = models.Address.objects.filter(uid=op)
    print(addrs)
    for i in addrs:
        if i.id != addr.id:
            i.isChecked=0
            i.save()
    return HttpResponse('<script>alert("设置成功");location.href="'+reverse('myhome_myinfo_address')+'"</script>')




# 收货地址修改
def myinfo_addressedit(request):
    # 获取所有的一级城市数据
    citys = models.Citys.objects.filter(level=1)
    # 获取当前用户的要修改的收货地址
    data = models.Address.objects.get(id=request.GET.get('uid'))
    try:
        if request.method == 'GET':
            data.sheng = models.Citys.objects.get(id=data.sheng).name
            data.shi = models.Citys.objects.get(id=data.shi).name
            data.xian = models.Citys.objects.get(id=data.xian).name
            # 分配数据
            context={'data':data,'citys':citys}

            return render(request,'myhome/myinfo/addredit.html',context)

        elif request.method == 'POST':
            data.shr = request.POST.get('shr')
            data.shdh = request.POST.get('shdh')
            data.sheng = request.POST.get('sheng')
            data.shi = request.POST.get('shi')
            data.xian = request.POST.get('xian')
            data.info =  request.POST.get('info')
            data.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myhome_myinfo_address')+'"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");history.back(-1)</script>')




 
# 获取城市信息
def getcitys(request):
    # 根据id获取下一级的城市数据,返回json数据
    data = models.Citys.objects.filter(upid = request.GET.get('id')).values()
    print(data)
    # 解析json 
    return JsonResponse(list(data),safe=False)



# 收货地址添加
def addressadd(request):
    # 接受地址信息
    data = request.GET.dict()
   
    # 获取当前用户对象
    data['uid'] = models.Users.objects.get(id = request.session['Vip']['id'])
    # 进行数据存储
    ob = models.Address(**data)
    ob.save()
    return JsonResponse("{'msg':'添加成功'}",safe=False)




# 收货地址获取
def addresslist(request):
    try:
        # 获取当前用户的所有收货地址
        data = models.Address.objects.filter(uid=request.session['Vip']['id']).values()
        for x in data:
            x['sheng'] = models.Citys.objects.get(id=x['sheng']).name
            x['shi'] = models.Citys.objects.get(id=x['shi']).name
            x['xian'] = models.Citys.objects.get(id=x['xian']).name
        #返回数据
        return JsonResponse({'error':0,'data':list(data)},safe=False)
    except:
        return JsonResponse({'error':1,'msg':'当前用户没有收货地址'})





# 显示商品详情页
def cartindex(request):
    try:
        # 获取当前
        data = models.Cart.objects.filter(uid = request.session['Vip']['id'])
        print(data)
        # 分配数据
        context = {"data":data}
        return render(request,'myhome/cart.html',context)
    except:
        return HttpResponse('<script>alert("请先登录");history.back(-1)</script>')




# 设置默认地址
def setaddress(request):
    # 获取想要设置地址的默认地址
    aid = request.GET.get('aid')
    addr = models.Address.objects.get(id=aid)
    addr.isChecked=1
    addr.save()
    op = models.Users.objects.get(id=request.session['Vip']['id'])
    addrs = models.Address.objects.filter(uid=op)
    print(addrs)
    for i in addrs:
        if i.id != addr.id:
            i.isChecked=0
            i.save()
    return JsonResponse({'error':0,'msg':'设置成功'})




# 删除地址
def addressdel(request):
    ob = request.GET.get('addressid')
    print(ob)
    data = models.Address.objects.get(id = ob)
    if data.isChecked == True:
        # print(1111)
        # return HttpResponse('<script>alert("默认地址不能删除,请先解除默认");</script>')
        return HttpResponse('<script>alert("默认地址不能删除,请先解除默认");</script>')

    else:
        data.delete()
        return JsonResponse({'error':0,'msg':'删除成功'})




# 注册
def register(request):
    if request.method == "GET":
        return render(request,'myhome/register.html')
    else:
        try:
            # ----------------------------------------------------
            # 验证手机的验证码是否正确

            # 判断手机号和密码是否为空
            if request.POST['phone'] == '' or request.POST['password'] == '' or request.POST['passwordRepeat'] == '0':
                return HttpResponse('<script>alert("手机号或密码不能为空");location.href="'+ reverse('myhome_register') +'"</script>')
            # 判断密码与确认密码是否一致
            if request.POST['password'] != request.POST['passwordRepeat']:
                return HttpResponse('<script>alert("密码与确认密码不一致");location.href="'+ reverse('myhome_register') +'"</script>')
            # 验证手机号和验证码是否和session中一致
           
            if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != request.session['msgcode']['code']:
                # 满足以上两个条件中的任意一个条件则验证码错误
                return HttpResponse('<script>alert("注册失败,验证码错误");location.href="'+ reverse('myhome_register') +'"</script>')
            # 不满足则验证码正确


            # ----------------------------------------------------
            # 密码加密
            password  = make_password(request.POST['password'], None, 'pbkdf2_sha256')
            # 生成随机的用户名
            username = 'user'+str(request.POST['phone'])
            data = {'username':username,'phone':request.POST['phone'],'password':password}
            
            # 执行注册
            ob = models.Users(**data)
            ob.save()
            # 跳转登录页面
            return HttpResponse('<script>alert("注册成功.请登录");location.href="'+reverse('myhome_login')+'"</script>')
        except:
            return HttpResponse('<script>alert("注册失败");location.href="'+reverse('myhome_register')+'"</script>')




# 验证手机号
def checkphone(request):
    # 接收手机号
    phone = request.GET.get('phone')
    # 到数据库查询
    num = models.Users.objects.filter(phone=phone).count()
    if num:
        return JsonResponse({'error':1,'msg':'手机号码已存在'})
    else:
        return JsonResponse({'error':0,'msg':'手机号码不存在'})


# 登录
def login(request):
    nextpath = request.GET.get('nextpath','/')
    args = eval(request.GET.get('args','{}'))
    a = ''
    for k,v in args.items():
        a += '&'+k+'='+v
    nexturl = nextpath+'?'+a
    if request.method == 'GET':
        return render(request,'myhome/login.html')
    else:
        # 执行登录
        try:
            # 先根据手机号获取用户
            ob = models.Users.objects.get(phone = request.POST['phone'])
            # 在对比密码是否正确
            res = check_password(request.POST['password'],ob.password)
            if res:
                # 用户名和密码是否正确
                # 在session中存入登录凭证
                request.session['Vip'] = {'username':ob.username,'phone':ob.phone,'id':ob.id,'pic_url':ob.pic_url}
                # 跳转到首页
                return HttpResponse('<script>alert("登录成功");location.href="'+nexturl+'"</script>')
            else:
                # 密码错误
                pass
        except:
            pass
            # 用户不存在
            
        return HttpResponse('<script>alert("用户名或密码错误");history.back(-1)</script>')



# 退出登录
def logout(request):
    del request.session["Vip"]
    return HttpResponse('<script>alert("退出登录");location.href="/";</script>')




# 发送手机验证码
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C41891116" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "d9dedfc7b6e9cd1a741821b6516cf143"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')

    # print(request.GET.get('phone')+'asasasd')
    # 随机验证码
    code = str(random.randint(10000,99999))
    print(code)
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    # text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # # 发起 请求
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # # 获取响应内容
    # content =req.read()
    # # 解析结果
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')


# 文件上传函数
def uploads(myfile):
    filename = str(time.time())+'.'+myfile.name.split('.').pop()
    destination = open(BASE_DIR+'/static/pics/'+filename,'wb+')
    for chunk in myfile.chunks():
        destination.write(chunk)
    destination.close()
    return "/static/pics/"+filename
